<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/7/13
 * Time: 17:01
 */

namespace App\Http\Controllers\API\Course;


use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\Classes;
use App\Models\ClassStudent;
use App\Models\Course;
use App\Models\CourseTime;
use App\Models\ElectiveClassGroup;
use App\Models\Semester;
use App\Models\Student;
use App\Models\StudentCourse;
use App\Models\StudentLog;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class CourseController extends Controller
{
    private $opening = '';
    private $user = 0;
    private $year_id = '';
    private $weeks = 0;
    private $errorNum = 0;
    private $successNum = 0;
    private $colors = [
        '#ec6d71',
        '#eb6ea5',
        '#d7cf3a',
        '#c3d825',
        '#2792c3',
        '#d9333f',
        '#5383c3',
        '#f8b862',
        '#f08300',
        '#ec6d51',
        '#884898',
        '#ffea00',
        '#e2041b',
        '#008899',
        '#ggec47',
        '#e45e32',
        '#cd5e3c',
        '#bb5548',
        '#59b9c6',
        '#ee7948'
    ];
    private $weekDays = ['一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5, '六' => 6, '七' => 7];

    /**
     * 导入课程
     * @param Request $request
     */

    public function import(Request $request)
    {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "1024M");
        $this->user = $request->get('user');
        if ($request->ajax()) {
            $year_id = $request->get('opening');
            $this->year_id = $year_id;

            $year = Semester::query()->where('id', $year_id)->first();
            $this->weeks = $year->s_week;
            $this->opening = $year->begin;
            $file = $request->file('file');
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'daoru.' . $extension;
            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            Excel::load($savePath . '/' . $filename, function ($reader) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                //  dd($results);
                foreach ($results as $key => $items) {
                    if ($key == 0) {
                        continue;
                    }
                    $kch = $items[1];
                    $kxh = $items[2];
                    $kz = $items[3];
                    $kcm = $items[4];
                    $js = $items[5];
                    $jsh = $items[6];
                    $weeklists = $items[7];
                    $weekday = $this->weekDays[trim($items[8])];
                    $jieshu = $items[9];
                    $place = $items[10];
                    \DB::beginTransaction();
                    try {
                        $coure = DB::table('courses')->where([
                            'semester_id' => $this->opening,
                            'c_number' => trim($kch),
                            'serial_number' => trim($kxh)
                        ])->first();
                        if (!$coure) {
                            $coure = new Course();
                            $coure->c_number = $kch;
                            $coure->serial_number = $kxh;
                            $coure->c_name = $kcm;
                            $coure->semester_id = $this->opening;
//                            $coure->teacher = $items[13];
//                            $coure->place = $items[15];
                            if (!$coure->save()) {
                                throw new \Exception(var_dump($coure->getErrors()));
                            }
                        }
                        if ($jieshu) {
                            $weeks = $this->getWeekDays($weeklists, $this->weeks);
                            $opening = strtotime($this->opening);
                            $classGroup = ElectiveClassGroup::query()->where(['class_group_name' => $kz])->first();
                            if (!$classGroup) {
                                $classGroup = new ElectiveClassGroup();
                                $classGroup->class_group_name = $kz;
                                if (!$classGroup->save()) {
                                    throw new \Exception(var_dump($classGroup->getErrors()));
                                }
                            }
                            foreach ($weeks as $week) {
                                $countweekclasses = $this->getWeekDays($jieshu, 0);
                                //   dd($jieshu,$countweekclasses);
                                foreach ($countweekclasses as $a) {
                                    $log = CourseTime::query()
                                        ->where([
                                            'school_year' => $this->year_id,
                                            'weeks' => $week,
                                            'days' => $weekday,
                                            'c_id' => $coure->id,
                                            'lessons' => $a,
                                            'place' => $place,
                                            'teacher' => $js
                                        ])->first();
                                    if (!$log) {
                                        $time = $opening + ((int)$week - 1) * 7 * 24 * 3600 + ($weekday - 1) * 24 * 3600;
                                        $log = new CourseTime();
                                        $log->c_id = $coure->id;
                                        $log->lessons = $a;
                                        $log->weeks = (integer)$week;
                                        $log->days = $weekday;
                                        $log->teacher = $js;
                                        $log->place = $place;
                                        $log->school_year = $this->year_id;
                                        $log->class_group_id = $classGroup->id;
                                        $log->date = $time;
                                        if (!$log->save()) {
                                            throw new \Exception(var_dump($log->getErrors()));
                                        }
                                    }
                                }
                            }
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        \DB::rollback();
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = $this->user;
                $logs->logs = '导入课程信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入成功', 200);
                }

            });
//            return ;
        }
    }

    /**
     * 导入选课结果
     * @param Request $request
     */
    public function select(Request $request)
    {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "1024M");
        if ($request->ajax()) {
            $this->user = $request->get('user');
            $year_id = $request->get('opening');
            $file = $request->file('file');
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'daoru.' . $extension;
            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            //   dd($savePath . '\\' . $filename);
            Excel::load($savePath . '/' . $filename, function ($reader) use ($year_id) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                foreach ($results as $key => $items) {
                    $xuehao = $items[5];
                    $banji = $items[33];
                    $kch = $items[1];
                    $kcm = $items[2];
                    $kxh = $items[4];
                    if ($key == 0 || empty($xuehao) || empty($banji) || empty($kch) || empty($kxh)) {
                        continue;
                    }
                    \DB::beginTransaction();
                    try {
//                        $class = Classes::query()
//                            ->where('c_name', $banji)
//                            ->first();
//                        if (!$class) {
//                            $class = new Classes();
//                            $class->c_name = $banji;
//                            if (strpos($banji, "业务") !== false) {
//                                $class->type = 1;
//                            } else {
//                                $class->type = 2;
//                            }
//                            if (!$class->save()) {
//                                throw new \Exception('班级创建失败');
//                            }
//                        }
                        $student = Student::query()->where('u_code', $xuehao)
                            ->first();
                        if (!$student) {
                            $student = new Student();
                            $student->u_name = $items[6];
                            $student->u_code = $xuehao;
                            $student->school = $items[35];
                            $student->access_token = str_random(60);
                            if (!$student->save()) {
                                throw new \Exception('绑定学生失败');
                            }
                        }
//                        ClassStudent::query()->where('s_id', $student->id)->delete();
//                        $log = new ClassStudent();
//                        $log->s_id = $student->id;
//                        $log->c_id = $class->id;
//                        if (!$log->save()) {
//                            throw new \Exception('绑定学生学校失败');
//                        }
                        $course = DB::table('courses')->where([
                            'semester_id' => $year_id,
                            'c_number' => trim($kch),
                            'serial_number' => trim($kxh)
                        ])->first();
                        if (!$course) {
                            if (!$course) {
                                $course = new Course();
                                $course->c_number = trim($kch);
                                $course->serial_number = trim($kxh);
                                $course->semester_id = $year_id;
                                $course->c_name = $kcm;
                                if (!$course->save()) {
                                    throw new \Exception('课程保存失败');
                                }
                            }
                        }
                        $log = StudentCourse::query()->where([
                            's_id' => $student->id,
                            'c_id' => $course->id,
                            'semester_id' => $year_id
                        ])->first();
                        if (!$log) {
                            $colors = $this->getColors($student->id, $year_id);
                            $log = new StudentCourse();
                            $log->s_id = $student->id;
                            $log->c_id = $course->id;
                            $log->semester_id = $year_id;
                            $log->color = $colors;
                            if (!$log->save()) {
                                throw new \Exception('课程绑定学员失败');
                            }
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        dd($e);
                        \DB::rollBack();
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = $this->user;
                $logs->logs = '导入选课结果信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入成功', 200);
                }
            });

//            return ;
        }
    }

    /**
     * 搜索课程表
     * @param Request $request
     */

    public function schedule(Request $request)
    {

        $week = $request->get('weeks', 1);
        $open = $request->get('open_id');
        $years = $request->get('year', 1);
        $reult = [];
        try {
            if (!$open) {
                throw new \Exception('OpenID不能为空');
            }
            $student = Student::query()->where(['wx_key' => $open])->first();
            if (!$student) {
                throw new \Exception('未绑定/未录入系统');
            }
            for ($a = 0; $a < 7; $a++) {
                for ($b = 0; $b < 10; $b++) {
                    $items[$b] = (object)array();
                }
                $reult[$a] = $items;
            }
            for ($a = 1; $a <= 7; $a++) {
                $courses = \DB::table('courses')->join('course_times', function ($join) {
                    $join->on('courses.id', '=', 'course_times.c_id');
                })->where([
                    'course_times.weeks' => $week,
                    'course_times.school_year' => $years,
                    'course_times.days' => $a
                ])
                    ->join('student_courses', function ($join) {
                        $join->on('student_courses.c_id', '=', 'courses.id');
                    })->where([
                        'student_courses.s_id' => $student->id,
                        'student_courses.semester_id' => $years
                    ])->orderBy('course_times.lessons')
                    ->get();
                if ($courses) {
                    foreach ($courses as $items) {
                        $reult[$a - 1][$items->lessons - 1] = $items;
                    }
                }
            }
            $log = new StudentLog();
            $log->student_id = $student->id;
            $log->logs = '通过微信端查看了课程表';
            if (!$log->save()) {
                throw new \Exception('记录添加失败');
            }
//            dd($reult);
            return \GuzzleHttp\json_encode($reult, true);
        } catch (\Exception $e) {
            return response($e->getMessage(), 406);
        }

    }

    public function getWeekDays($str, $weeks)
    {
        $list = preg_replace('/([\x80-\xff]*)/i', '', $str);
        if (!$list) {
            for ($a = 1; $a <= $weeks; $a++) {
                $result[] = (int)$a;
            }
        } else {
            $list = explode(',', $list);
            $result = [];
            foreach ($list as $items) {
                $item = explode('-', $items);
                if (count($item) > 1) {
                    for ($a = $item[0]; $a <= $item[1]; $a++) {
                        $result[] = (int)$a;
                    }
                } else {
                    $result[] = (int)$item[0];
                }
            }
        }

        return $result;
    }

    public function getList()
    {
        $Courses = Course::query()->get();
        $result = [];
        if ($Courses) {
            foreach ($Courses as $items) {
                $result[$items->id] = $items->c_name;
            }
        }
        return $result;
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $select = $request->get('select', '');
        $query = Course::query()->with('Semesters')
            ->where('c_name', 'like', '%' . $queryString . '%');
        if (!empty($select)) {
            $query->where(['semester_id' => $select]);
        }
        $models = $query->paginate();
        return $models;
    }

    public function getColors($id, $year_id)
    {
        $c = $this->colors[array_rand($this->colors, 1)];
        $log = StudentCourse::query()->where(['s_id' => $id, 'color' => $c, 'semester_id' => $year_id])->first();
        if ($log) {
            return $this->getColors($id, $year_id);
        } else {
            return $c;
        }
    }

    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Course();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Course $Course, Request $request)
    {
        $Course->fill($request->all());
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改课程信息：' . $Course->c_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($Course->save()) {
            return $Course;
        } else {
            return response($Course->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除课程信息：' . $model->c_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show(Course $course)
    {
        return $course;
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Course::findOrFail($id);
        return $model;
    }
}